package com.kalvin.kvf.common.utils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.yaml.snakeyaml.Yaml;

/**
yml文件配置参数获取工具类

例如：application.yml
---------------------------------------
a:
	b:
		c:
		    d: hahah
		    e: heheh
		    f: heiheihei
g: xixixi
 ---------------------------------------
		key的格式:
		假如：获取d的值，key的格式为：a.b.c.d
		假如：获取g的值，key的格式为：g

*/

public class YamlReaderUtil {

	private static  Logger log = LogManager.getLogger(YamlReaderUtil.class);

	private static Map<String, Map<String, Object>> properties = new HashMap<>();
 
	/**
	 * 单例
	 */
	public static final YamlReaderUtil instance = new YamlReaderUtil();
 
	static {
		Yaml yaml = new Yaml();
		try (InputStream in = YamlReaderUtil.class.getClassLoader().getResourceAsStream("application-dev.yml");) {
			properties = yaml.loadAs(in, HashMap.class);
		} catch (Exception e) {
			log.error("Init yaml failed !", e);
		}
	}
 
	/**
	 * get yaml property
	 * 
	 * @param key
	 * @return
	 */
	public Object getValueByKey(String key) {
		String separator = ".";
		String[] separatorKeys = null;
		if (key.contains(separator)) {
			separatorKeys = key.split("\\.");
		} else {
			return properties.get(key);
		}
		Map<String, Map<String, Object>> finalValue = new HashMap<>();
		for (int i = 0; i < separatorKeys.length - 1; i++) {
			if (i == 0) {
				finalValue = (Map) properties.get(separatorKeys[i]);
				continue;
			}
			if (finalValue == null) {
				break;
			}
			finalValue = (Map) finalValue.get(separatorKeys[i]);
		}
		return finalValue == null ? null : finalValue.get(separatorKeys[separatorKeys.length - 1]);
	}


}
